package com.scheduler.utils.okhttp;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;


public class ThrowableUtil {
    /**
     * 将堆栈转为字符串输出
     */
    public static String toStackString(Throwable throwable) {
        return toStackString(throwable, 1000);
    }

    public static String toStackString(Throwable throwable, int maxLength) {
        if (throwable == null) {
            return null;
        }
        try (Writer writer = new StringWriter();
             PrintWriter printWriter = new PrintWriter(writer);) {
            throwable.printStackTrace(printWriter);
            String string = writer.toString();
            if (string.length() > maxLength) {
                // 此处截取后半段的，用于能够识别到Caused by里面的错误信息
                return string.substring(0, maxLength);
            }
            return string;
        } catch (IOException e) {
            e.printStackTrace();
            return throwable.toString();
        }
    }

    public static String toMessageStringRootCause(Throwable throwable) {
        return toMessageStringRootCause(throwable, 300);
    }

    public static String toMessageStringRootCause(Throwable throwable, int maxLength) {
        if (throwable == null) {
            return null;
        }
        Throwable rootCause = findRootCause(throwable);
        String message = rootCause.toString();
        if (message.length() > maxLength) {
            // 此处截取后半段的，用于能够识别到Caused by里面的错误信息
            return message.substring(0, maxLength);
        }
        return message;
    }

    public static Throwable findRootCause(Throwable throwable) {
        return throwable == null ? null : (throwable.getCause() == null ? throwable : findRootCause(throwable.getCause()));
    }
}
